package com.example.seckill.controller;

import com.example.seckill.result.SeckillResult;
import com.example.seckill.service.SeckillLoadBalancer;
import com.example.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


/**
 * 三面题：500个人去抢一瓶茅子，两个服务器，一台服务器负载300，数据库负载10，设计一个秒杀系统
 */
@RestController
@RequestMapping("/api/seckill")
@Slf4j
public class SeckillController {
    
    @Autowired
    private SeckillService seckillService;
    
    @Autowired
    private SeckillLoadBalancer seckillLoadBalancer;
    
    /**
     * 秒杀接口
     */
    @PostMapping("/kill")
    public SeckillResult seckill(@RequestParam Long userId,
                                 @RequestParam Long productId) {
        
        // 记录请求信息
        String serverName = seckillLoadBalancer.selectServer();
        log.info("服务器{}接收到用户{}的秒杀请求", serverName, userId);
        
        // 参数校验
        if (userId == null || productId == null) {
            return SeckillResult.fail("参数不能为空");
        }
        
        // 执行秒杀
        SeckillResult result = seckillService.seckill(userId, productId);
        
        log.info("用户{}秒杀结果：{}", userId, result.getMessage());
        return result;
    }
    
    /**
     * 查询库存接口
     */
    @GetMapping("/stock/{productId}")
    public SeckillResult getStock(@PathVariable Long productId) {
        int stock = seckillService.getCurrentStock(productId);
        return SeckillResult.success(stock);
    }
    
    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public Map<String, Object> health() {
        Map<String, Object> result = new HashMap<>();
        result.put("status", "UP");
        result.put("server", seckillLoadBalancer.selectServer());
        result.put("timestamp", System.currentTimeMillis());
        return result;
    }
}
